import json
import os
import time

import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.webdriver import WebDriver


def loadCookie(driver: WebDriver, cookieFile: str):
    try:
        if not os.path.exists(cookieFile):
            return False

        file = open(cookieFile, 'r')

        cookie_str = file.read()
        file.close()

        cookies = json.loads(cookie_str)
        if len(cookies) == 0:
            return False

        for cookie in cookies:
            driver.add_cookie(cookie)

        driver.refresh()

        return True
    except Exception as e:
        print(e.__str__())

        return False


def createChromeInstance():
    chrome_options = webdriver.ChromeOptions()
    # chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')

    # 将--user-data-dir改为自定义目录
    # 在linux服务器上执行，需要增加
    # chrome_options.add_argument("--user-data-dir=/root/facebook")
    # s = Service(executable_path='/usr/local/bin/chromedriver')

    s = Service(executable_path='/Users/gilbert/chromedriver-mac-x64/chromedriver')
    _chrome_driver_instance = webdriver.Chrome(service=s, options=chrome_options)

    _chrome_driver_instance.get("https://www.facebook.com")

    time.sleep(3)

    if loadCookie(_chrome_driver_instance, "/Users/gilbert/facebook/facebook.cookie"):
        return _chrome_driver_instance
    else:
        _chrome_driver_instance.quit()

        return None


def scrapyFacebookInfo(url: str):
    driver = createChromeInstance()
    if not driver:
        print("create chrome instance failed.")

        return

    try:
        driver.get(url)

        time.sleep(3)
    except Exception as e:
        print(e.__str__())
    finally:
        driver.quit()


if __name__ == '__main__':
    scrapyFacebookInfo("https://www.facebook.com/FTVNews53")




